<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true">
      <el-form-item label="渠道" prop="companyName">
        <el-input
          v-model="queryParams.companyName"
          placeholder="请输入渠道"
          clearable
          size="small"
          style="width: 200px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="联系人" prop="contact">
        <el-input
          v-model="queryParams.contact"
          placeholder="请输入联系人"
          clearable
          size="small"
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="联系人电话" prop="contactPhone">
        <el-input
          v-model="queryParams.contactPhone"
          placeholder="请输入联系人电话"
          clearable
          size="small"
          style="width: 200px"
          @keyup.enter.native="handleQuery"
        />
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择状态"
            clearable
            size="small"
            style="width: 200px"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
                   v-hasPermi="['setting:company:query']">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['setting:company:add']"
        >新增渠道商</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-c-scale-to-original"
          size="mini"
          @click="handleSetPercent"
          v-hasPermi="['setting:company:percent']"
        >设置渠道人员比例
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-setting"
          size="mini"
          @click="handleSetPrice"
          v-hasPermi="['workerJob:company_price:list']"
        >时段价格设置
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="companyList" @selection-change="handleSelectionChange" >
      <el-table-column type="selection" width="150" align="center" v-if="show"/>
      <el-table-column label="渠道编号" prop="id" align="center"  width="100"/>
      <el-table-column label="渠道名称" prop="company" :show-overflow-tooltip="true" width="200"/>
      <el-table-column label="联系人" prop="contact" :show-overflow-tooltip="true" width="150"/>
      <el-table-column label="联系人手机号" prop="contactPhone" width="150"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="150" v-if="show">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="招聘比例" prop="recruitPercent" width="100" :formatter="batteryformatter"/>
      <el-table-column label="备注"  prop="remark" width="150" />
      <el-table-column label="状态" align="center" width="150">
        <template slot-scope="scope">
          <div v-if="scope.row.status == 1">启用</div>
          <div v-else-if="scope.row.status == 2">禁用</div>
        </template>
      </el-table-column>


      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['setting:company:edit']"
          >编辑</el-button>

          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            :loading="exportLoading"
            @click="handleQrcodeImg(scope.row)"
            v-hasPermi="['setting:company:applet']"
          >小程序
          </el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['setting:company:delete']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改渠道对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="780px" append-to-body>
      <el-form ref="form" :model="form" label-width="100px" :rules="rules" label-position="right">
        <el-row>
          <el-col :span="12">
            <el-form-item label="渠道名称" prop="company">
              <el-input v-model="form.company" placeholder="请输入渠道名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contact">
              <el-input v-model="form.contact" placeholder="请输入联系人" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
          <el-form-item label="联系电话" prop="contactPhone">
            <el-input v-model="form.contactPhone" placeholder="请输入联系人电话" />
          </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="招聘比例" prop="recruitPercent" >
              <el-input v-model="form.recruitPercent" :disabled="true">
                <i slot="suffix" style="margin-right: 10px;">%</i>
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.label"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
<!--          <el-col :span="12">
            <el-form-item label="渠道商价格" label-width="96px">
              <el-radio-group v-model="form.priceStatus">
                <el-radio
                  v-for="dict in priceStatusOptions"
                  :key="dict.label"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>-->
<!--          <el-col :span="12">
            <el-form-item label="白班价格">
              <el-input-number style="width: 100%" v-model="form.dayPrice" :min="0" :disabled="form.priceStatus===2"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="夜班价格">
              <el-input-number style="width: 100%" v-model="form.nightPrice" :min="0" :disabled="form.priceStatus===2"></el-input-number>
            </el-form-item>
          </el-col>-->


          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--修改渠道比例-->
    <el-dialog title="渠道比例" :visible.sync="setPercent" width="780px" append-to-body>
      <el-table :data="enableCompanyList" border show-summary  :summary-method="getSummaries">
        <el-table-column label="渠道名称" prop="company" width="500px"/>
        <el-table-column label="人员比例" prop="recruitPercent" :show-overflow-tooltip="true" width="238px">
          <template slot-scope="{row,$index}">
            <el-input class="edit-cell"  placeholder="请输入人员比例" v-model="row.recruitPercent">
              <i slot="suffix" style="margin-right: 10px;">%</i>
            </el-input>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitRecruitPercentForm">确认</el-button>
      </div>
    </el-dialog>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

  </div>
</template>

<script>
import {listCompanyList,exportInfos,changeStatus,insert,getCompany,delCompany,update,updateRecruitPercent,getQrCodeImg} from "@/api/job/company/companyApi";
import {saveNumber} from '@/api/job/jobset/jobSet';
export default {
  name: "company",
  data() {
    return {
      // 日期范围
      dateRange: [],
      companyId:0,
      setPercentLoading:true,
      show: false,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      companyList: [],
      //启用渠道表格数据
      enableCompanyList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,

      //合计的值
      totalPercent : 0,
      setPercent:false,
      // 黑名单下拉
      statusOptions: [{value: 1, label: '启用'}, {value: 2, label: '禁用'}],
      priceStatusOptions: [{value: 0, label: '启用'}, {value: 2, label: '禁用'}],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        //渠道名称
        companyName: undefined,
        //联系人
        contact: undefined,
        //联系人手机号码
        contactPhone: undefined,
        //
        recruitPercent:undefined,
        //状态
        status: undefined
      },
      timeShiftList:[],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },

      rules: {
        company: [
          { required: true, message: "渠道商名称不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '渠道商名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        contact: [
          { required: true, message: "渠道商联系人不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '渠道商联系人长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        contactPhone: [
          {required: true,
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      }
    };
  },
  created() {

   this.getList();
  },
  methods: {

    /** 获取员工信息列表 */
    getList() {
      this.loading = true;

      listCompanyList(this.addDateRange(this.queryParams, this.dateRange)).then(
        response => {
          this.companyList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    //黑名单
    handleStatusChange(row) {
      let text = row.status == "2" ? "停用" : "启用";
      this.$confirm('确认要"' + text + '""' + row.company + '"吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return changeStatus(row.id, row.status);
      }).then(() => {
        this.msgSuccess(text + "成功");
      }).catch(function () {
        row.status = row.status === "0" ? "1" : "0";
      });
    },

    // 表单重置
    reset() {
        this.form = {
          id:undefined,
          companyName: undefined,
          contact: undefined,
          contactPhone: undefined,
          recruitPercent:undefined,
          status: undefined,
          remark: undefined,
          createTime: undefined,
          menuCheckStrictly: true,
          deptCheckStrictly: true,
        };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.roleId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },

    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有员工数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return exportInfos(queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {
      });
    },

    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加渠道信息";
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            update(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            insert(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCompany(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改渠道信息";
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id || this.ids
      this.$confirm('是否确认删除渠道编号为"' + id + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delCompany(id);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {});
    },

    handleSetPercent() {
      this.setPercent = true;
      const setPercentParams={
        status: 1
      }

      listCompanyList(this.addDateRange(setPercentParams, this.dateRange)).then(
        response => {
          this.enableCompanyList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },

    //跳转至渠道商时段价格记录页面
    handleSetPrice() {
      this.$router.push({path: "/basic/personnel/company_price"});
    },

    // getTimeShiftList(row) {
    //   let companyId=this.companyId = row.id;
    //   this.signUpLoading = true;
    //   this.signUp = true;
    //   listTimeShiftList({companyId}).then(
    //     response => {
    //       this.timeShiftList = response.rows;
    //       this.total = response.total;
    //       this.signUpLoading = false;
    //     }
    //   );
    // },
    handleQrcodeImg(row){
      this.exportLoading = true;
      getQrCodeImg(row.id,row.company).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {
      });
    },
    saveNeedNumber(type,sex,number) {
      saveNumber(this.companyId,type,sex,number).then(response=>{
        this.msgSuccess("报名名额设置成功");
        this.getList();
      })
    },

    batteryformatter(row){
      if(row.recruitPercent==null){
        row.recruitPercent=0;
      }
      return row.recruitPercent+"%";
    },

    getSummaries(param){
      this.totalPercent =0.0;
      const { columns, data } = param;
      const sums = {};
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          if(column.property=="recruitPercent"){
            this.totalPercent = sums[index];
          }
          sums[index] += ' %';
        } else {
          sums[index] = 'N/A';
        }
      });
      return sums;
    },

    submitRecruitPercentForm() {
      if (this.totalPercent > 100) {
        alert('比例总和超过100%');
        return false;
      } else if (this.totalPercent < 100) {
        alert('比例总和不足100%');
        return false;
      };

      updateRecruitPercent(this.enableCompanyList).then(response => {
        this.msgSuccess("修改成功");
        this.setPercent = false;
        this.getList();
      });
    },
  }
};
</script>
